package com.easymin.weixin.service.impl;

import com.easymin.weixin.entity.Application;
import com.easymin.weixin.entity.ApplicationCriteria;
import com.easymin.weixin.mapper.ApplicationMapper;
import com.easymin.weixin.mapper.BaseMapper;
import com.easymin.weixin.service.ApplicationService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class DefaultApplicationService extends AbstractBaseService<Application, ApplicationCriteria, Long> implements ApplicationService {

  @Autowired
  private ApplicationMapper applicationMapper;

  @Override
  public BaseMapper<Application, ApplicationCriteria, Long> getMapper() {

    return applicationMapper;
  }

  @Override
  public boolean exists(String name) {

    ApplicationCriteria applicationCriteria = new ApplicationCriteria();
    applicationCriteria.createCriteria().andNameEqualTo(name);

    long total = applicationMapper.countByExample(applicationCriteria);

    return total > 0;
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public int insert(Application application) {

    application.setCreated(new Date());
    application.setUpdated(new Date());
    application.setVersion(1);

    return super.insert(application);
  }

  @Override
  public int update(Application application) {

    application.setUpdated(new Date());
    return super.update(application);
  }

  @Override
  public Application fetchByAppId(String appId) {

    ApplicationCriteria applicationCriteria = new ApplicationCriteria();
    applicationCriteria.createCriteria().andAppIdEqualTo(appId);

    List<Application> applications = applicationMapper.selectByExample(applicationCriteria);

    if (null != applications && applications.size() > 0) {
      return applications.get(0);
    }

    return null;
  }
}
